import { useEffect } from 'react'
import { useDispatch } from 'react-redux'
import { useSelector } from 'react-redux'
import { getChannel, setActive } from './store/action/channel'
import { getArticles } from './store/action/news'
import defaultCover from './assets/defaultCover.jpg'

export default function App() {
  return (
    <>
      {/* 头部频道 */}
      <Channel />
      {/* 文章列表 */}
      <News />
    </>
  )
}

function Channel() {
  // 获取频道模块的数据
  const { list, active } = useSelector((state) => state.channel)
  // console.log({ list, active })
  const dispatch = useDispatch()

  useEffect(() => {
    dispatch(getChannel())
  }, [dispatch])

  return (
    <ul className='catagtory'>
      {list.map((item, index) => (
        <li
          key={item.id}
          className={active === index ? 'select' : ''}
          // 点击修改 active 的值，实现高亮
          onClick={() => dispatch(setActive(index))}
        >
          {item.name}
        </li>
      ))}
    </ul>
  )
}

function News() {
  const dispatch = useDispatch()
  const { active } = useSelector((state) => state.channel)

  const { list } = useSelector((state) => state.news)

  // 频道的 active 变化时，重新获取文章列表
  useEffect(() => {
    dispatch(getArticles(active))
  }, [dispatch, active])

  return (
    <div className='list'>
      {/* 列表渲染 */}
      {list.map((item) => (
        <div key={item.art_id} className='article_item'>
          <h3 className='van-ellipsis'>{item.title}</h3>
          <div className='img_box'>
            <img
              src={item.cover.type === 0 ? defaultCover : item.cover.images[0]}
              className='w100'
              alt=''
            />
          </div>
          <div className='info_box'>
            <span>{item.aut_name}</span>
            <span>{item.comm_count}评论</span>
            <span>{item.pubdate}</span>
          </div>
        </div>
      ))}
      {/* 如果数据有数据，隐藏空提示 */}
      <div hidden={list.length} style={{ textAlign: 'center', padding: 20 }}>
        没有更多了...
      </div>
    </div>
  )
}
